<template>
  <div class="index-wrap">
    <div class="header">
      <div
        class="header--background"
        :style="{ backgroundImage: `url(${skin.homeTopBackgroud})` }"
      >
        <div class="flex">
          <div
            class="search"
            :style="{
              borderColor: skin.homeSearchBorderColor
            }"
            @click="toSearch"
          >
            <div class="search-center">
              <img :src="skin.homeSearchIconImg || searchIcon" />
              <div v-if="darkKeysList.length > 0" class="marquee_box">
                <ul
                  class="marquee_list"
                  :class="{ marquee_top: darkKeyAnimate }"
                >
                  <li v-for="(keyItem, index) in darkKeysList" :key="index">
                    {{ keyItem.searchWords }}
                  </li>
                </ul>
              </div>
              <div v-else class="default-key-wrap">
                {{ defaultPlaceHolder }}
              </div>
            </div>
            <div
              class="search-btn"
              :style="{ backgroundColor: skin.homeSearchBtnColor }"
              @click.stop="toSearch('btn')"
            >
              搜索
            </div>
          </div>
          <div
            class="brand-bg"
            :class="{ 'brand-bg-opacity': skin.skinStatus != 1 }"
            :style="{ backgroundColor: skin.homeBrandBackColor }"
          ></div>
          <div class="brand">
            <img :src="skin.homeBrandIconImg || brandIcon" />
            <p :style="{ color: skin.homeBrandTextColor }">
              品牌
            </p>
          </div>
        </div>
        <van-tabs
          ref="refName"
          v-model="curTab.index"
          active-color="#fff"
          inactive-color="#fff"
          class="header__tabs--category-channel"
          :color="skin.tabSelectTextColor"
          :title-inactive-color="skin.tabNormalTextColor"
          :title-active-color="skin.tabSelectTextColor"
          @click="setCurTab"
          @disabled="onClickDisabled"
        >
          <van-tab
            v-for="(item, index) in tabArr"
            :key="index"
            :title="item.activityTagName"
            :disabled="item.type === 2"
          />
        </van-tabs>
      </div>
      <!-- banner -->
      <div v-if="bannerInfo && bannerInfo.length > 0" class="index-banner">
        <common-banner
          :bannerList="bannerInfo"
          :bannerAutoplay="bannerAutoplay"
        />
      </div>
      <!-- 金刚位 -->
      <diamond-list
        v-if="diamondList.length && curTab.index === 0"
        :items="diamondList"
        @click="diamondListJump"
      />
      <!-- 胶囊位 -->
      <capsule @savePlugin="data => handleSavePlugin(data)" />
    </div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="content">
        <!-- 活动排序 -->
        <div class="DropdownMenu--wrap">
          <DropdownMenu :optionsArr="optionsArr" @getSort="clickHandle" />
        </div>

        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="好东西就到这里啦~"
          style="margin-bottom:50px;"
          @load="onLoad"
        >
          <div v-for="(item, i) in activityList" :key="i" style="width: 100%;">
            <insert-card
              v-if="item.isInsertCard"
              :insertCardObj="item"
              :index="i"
            />
            <activity v-else :index="i" :activityObj="item" />
          </div>
        </van-list>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import { Swipe, SwipeItem } from 'vant';
import activity from '@/components/activity.vue';
import DropdownMenu from '@/views/search/components/DropdownMenu.vue';
import commonBanner from './components/commonBanner.vue';
import insertCard from './components/insertCard.vue';
import DiamondList from './components/diamond-list.vue';
import capsule from './components/capsule/index.vue';
import searchIcon from '@/assets/icon_search_def.png';
import brandIcon from '@/assets/icon_brand.png';
import { http2https, getQueryParams, goLink } from '@/utils/util';
import { tabList, skinInfo } from './json/dataJson';
import { pageInfo } from './json/page';
import { resourceData1 } from './json/resource';

export default {
  name: 'index',
  components: {
    activity,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    DropdownMenu,
    DiamondList,
    commonBanner,
    insertCard,
    capsule
  },
  data() {
    return {
      darkKeyInterval: null,
      darkKeyAnimate: false,
      rollTime: 3000, // 暗词滚动时间间隔
      darkKeysList: [],
      noticeIndex: 0,
      isScroll: false,
      t1: 0,
      t2: 0,
      timer: null,
      fromPage: 'index',
      searchIcon,
      brandIcon,
      tabArr: [],
      curTab: {
        index: 0
      },
      pageObj: {
        pageNum: 1,
        pageSize: 10
      },
      isLoading: false, // 是否在加载中(下拉刷新)
      loading: false, // 是否处于加载状态，加载过程中不触发load事件
      finished: false, // 是否已加载完成，加载完成后不再触发load事件
      isFire: false, // 是否方法阻塞
      hasNextPage: true,
      scrollY: 0,
      sortObj: {
        sortedType: 2,
        sortedModel: '1'
      },
      optionsArr: [
        // 排序筛选（用户）
        {
          text: '综合',
          value: '1'
        },
        {
          text: '销量',
          value: '3',
          arrowType: 2
        },
        {
          text: '上新',
          value: '2',
          arrowType: 2
        }
      ],
      placeholderText: '',
      defaultPlaceHolder: '搜索商品款号、序号、关键字',
      diamondList: resourceData1.data.diamondList, // 金刚位
      /* banner轮播 属性开始 */
      bannerInfo: resourceData1.data.categoryBannerList,
      bannerAutoplay: 4000,
      /* banner轮播 属性结束 */
      smallSuperBanner: [], // 小胶囊位
      superBanner: [], // 大胶囊位
      conjoinedSuperBanner: [],
      pluginCards: [], // 插卡列表数据
      moduleType: 1,
      isAgent: false,
      timeId: null,
      hotKeyIndex: 0,
      skin: skinInfo.data || {},
      activityList: []
    };
  },
  computed: {
    tabName() {
      const { index } = this.curTab;
      const { activityTagName = '' } = this.tabArr[index || 0] || {};
      return activityTagName;
    }
  },
  methods: {
    handleSavePlugin(data) {
      this.pluginCards = data;
    },
    showMarquee() {
      this.darkKeyAnimate = true;
      setTimeout(() => {
        this.darkKeysList.push(this.darkKeysList[0]);
        this.darkKeysList.shift();
        this.darkKeyAnimate = false;
      }, 500);
    },
    http2httpsLocal(url) {
      return http2https(url);
    },
    onRefresh() {
      this.initData();
      this.isLoading = true;
      this.init();
    },
    initData() {
      this.pageObj.pageNum = 1;
      this.activityList = [];
      this.isLoading = false;
      this.loading = false;
      this.finished = false;
      this.isFire = false;
      this.diamondlistArr = [];
      this.pluginCards = [];
      this.smallSuperBanner = [];
      this.superBanner = [];
      this.moduleType = 1;
    },
    setCurTab(index) {
      // 处理路径上带的activityTagNo参数
      const { activityTagNo, ...rest } = this.$route.query;
      if (activityTagNo) {
        this.$router.replace({
          path: 'index',
          query: rest
        });
      }
      this.initData(); // 重置数据
      this.curTab = {
        ...this.tabArr[index],
        index
      };
      this.$nextTick(() => {
        this.initList();
      });
    },
    getActivity() {
      this.isFire = true;
      const res = pageInfo || {};
      if (res.code === 200) {
        res.data = res.data || {};
        const activityPage = res.data.activityPage || {};
        activityPage.list = activityPage.list || [];
        // 处理列表数据
        if (this.pageObj.pageNum === 1) {
          this.activityList = activityPage.list;
        } else {
          // 转发置顶后，为了防止c端数据重复，而进行去重
          const newActivityList = this.activityList;
          const actNoArr = newActivityList.map(item => item.activityNo);
          activityPage.list.forEach(item => {
            if (!actNoArr.includes(item.activityNo)) {
              newActivityList.push(item);
            }
          });
          this.activityList = newActivityList;
        }

        // 只有在全部栏目下进行插卡
        if (this.curTab.activityTagNo === '10') {
          // 搜集列表已存在的插卡Ids
          const cardIds = this.activityList
            .filter(item => item.isInsertCard)
            .map(item => item.id);
          // 已存在的插卡数
          let insertCardNum = cardIds.length || 0;
          // 剔除列表中存在的插卡
          const insertCardList = this.pluginCards.filter(
            item => !cardIds.includes(item.id)
          );
          // 将剩余的插卡位数据插入列表中
          // eslint-disable-next-line no-restricted-syntax
          for (const item of insertCardList) {
            if (this.activityList.length - insertCardNum >= item.location) {
              this.activityList.splice(item.location + insertCardNum, 0, item);
              insertCardNum += 1;
            } else {
              break;
            }
          }
        }
        this.finished = !activityPage.hasNextPage;
        if (!this.finished) {
          this.pageObj.pageNum += 1;
        }
      } else {
        this.finished = true;
        this.$toast.fail(res.message);
      }
    },
    initList() {
      this.$nextTick(() => {
        this.getActivity();
      });
    },
    init() {
      this.getTab();
    },
    toSearch(type) {
      // 当前暗词
      const curDarkKey =
        this.darkKeysList.length > 0 ? this.darkKeysList[this.noticeIndex] : {};
      this.$router.push({
        path: '/search',
        query: {
          isCamera: type === 'camera' ? '1' : '0',
          hotKey: curDarkKey.searchWords || '',
          source: curDarkKey.source || ''
        }
      });
    },
    // 获取类目列表
    getTab() {
      const res = tabList || {};
      this.tabArr = res.data || [];
      if (this.tabArr.length) {
        const { activityTagNo } = this.$route.query;
        let curIndex = 0;
        if (activityTagNo) {
          curIndex = this.tabArr.findIndex(
            item => item.activityTagNo === activityTagNo
          );
          console.log('index', curIndex);
          if (curIndex >= 0) {
            this.$nextTick(() => {
              this.curTab = {
                ...this.tabArr[curIndex],
                index: curIndex
              };
            });
          } else {
            curIndex = 0;
          }
        }
        this.curTab = { ...this.tabArr[curIndex], ...this.curTab };
        this.initList();
      } else {
        this.loading = false;
        this.finished = true;
      }
    },
    onLoad() {
      if (!this.curTab.activityTagNo) return;
      if (this.isFire || this.finished) {
        this.loading = false;
        return;
      }
      this.getActivity();
    },
    clickHandle(obj) {
      this.sortObj = { ...obj };
      this.finished = false;
      this.isFire = false;
      this.pageObj.pageNum = 1;
      this.getActivity();
    },
    diamondListJump(obj) {
      const { href = '' } = obj || {};
      // 链接跳转处理
      if (!href) return;
      // 完整链接跳转
      if (/^(http|https):\/\/([-.\w]+)\/(.+)/.test(href)) {
        goLink(href, (params, path) => {
          if (path === 'index') {
            return;
          }
          this.$router.push({
            path,
            query: {
              ...params,
              ...getQueryParams(href),
              shopId: this.$route.query.shopId
            }
          });
        });
      } else {
        const params = getQueryParams(href);
        const path = href.split('?')[0]; // 路由跳转path
        if (path) {
          this.$router.push({
            path,
            query: params
          });
        }
      }
    },
    onClickDisabled(index) {
      const href = this.tabArr[index] && this.tabArr[index].href;
      const params = getQueryParams(href);
      const path = href.split('?')[0]; // 路由跳转path
      if (path) {
        this.$router.push({
          path,
          query: params
        });
      }
    },
    handleIndexScroll() {
      this.isScroll = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(this.isScrollEnd, 500);
      this.t1 = document.documentElement.scrollTop || document.body.scrollTop;
    },
    isScrollEnd() {
      this.t2 = document.documentElement.scrollTop || document.body.scrollTop;
      if (this.t2 === this.t1) {
        this.isScroll = false;
      }
    },
    getDarkKeysHandle() {
      const { darkList, rollTime } = {};
      this.darkKeysList = darkList || [];
      if (rollTime) {
        this.rollTime = rollTime * 1000;
      }
      this.darkKeyInterval = setInterval(this.showMarquee, this.rollTime);
    }
  },
  created() {
    this.init();
  },
  mounted() {},
  activated() {
    this.getDarkKeysHandle();
    window.addEventListener('scroll', this.handleIndexScroll);
    const {
      isSwitchIdentify,
      isModifyPrice,
      modifyPriceInBrand
    } = this.$store.state;
    const reqFlag = isSwitchIdentify || isModifyPrice || modifyPriceInBrand;
    if (reqFlag) {
      this.getTab();
    }
  },
  deactivated() {
    if (this.darkKeyInterval) {
      clearInterval(this.darkKeyInterval);
    }
    window.clearTimeout(this.timeId);
    window.removeEventListener('scroll', this.handleIndexScroll);
    if (this.isShowPoster) {
      this.isShowPoster = false;
    }
  },
  beforeDestroy() {
    if (this.darkKeyInterval) {
      clearInterval(this.darkKeyInterval);
    }
    window.clearTimeout(this.timeId);
  }
};
</script>

<style lang="scss">
.header__tabs--category-channel {
  //padding-top: 36px !important;
  .van-tabs__wrap--scrollable .van-tab {
    flex: 0 0 auto !important;
    padding: 0 10px;
  }
  .van-tab--disabled {
    color: #7d7e80;
  }
  .van-tabs__wrap {
    height: 36px !important;
  }
  .van-tab {
    line-height: 36px !important;
  }
  .van-tabs__line {
    left: 0;
    bottom: 0;
    position: absolute;
    height: 2px !important;
    border-radius: 1px !important;
  }
  .van-tabs__nav--line {
    height: 100%;
    padding-bottom: 0;
    box-sizing: content-box;
  }
}

.header__tabs--category-channel {
  .van-tabs__nav {
    background-color: transparent;
  }
}
</style>

<style lang="scss" scoped>
.index-wrap {
  position: relative;
  min-height: 100vh;
  background: #f5f5f5;
  .header {
    margin-bottom: 8px;
    background-color: #fff;

    .header--background {
      background-repeat: no-repeat;
      background-size: cover;
      background-position: top left;
    }

    .flex {
      display: flex;
      align-items: center;
      padding: 10px 10px 6px;
      position: relative;

      .brand-logo {
        margin-left: -4px;
        margin-right: 8px;
        width: 30px;
        height: 30px;
        background: #fff;
        border-radius: 2px;
        overflow: hidden;
        img {
          width: 100%;
        }
      }

      .search {
        display: flex;
        align-items: center;
        margin-right: 8px;
        padding-left: 8px;
        height: 32px;
        width: 100%;
        background-color: #fff;
        border-radius: 16px;
        border: 2px solid #ff1010;
        position: relative;
        flex: 1;
        color: #666;
        box-sizing: border-box;

        .search-center {
          display: flex;
          align-items: center;
          position: relative;
          height: 100%;
          width: 100%;
          flex: 1;
        }

        img {
          margin-right: 4px;
          width: 18px;
          height: 18px;
        }
        .marquee_box {
          position: relative;
          width: 76%;
          height: 28px;
          overflow: hidden;
        }
        .marquee_list {
          position: absolute;
          top: 0;
          left: 0;
          li {
            height: 28px;
            font-size: 12px;
            display: flex;
            align-items: center;
          }
        }
        .marquee_top {
          transition: all 0.5s;
          margin-top: -28px;
        }
        .default-key-wrap {
          height: 28px;
          font-size: 12px;
          display: flex;
          align-items: center;
        }

        .search-btn {
          width: 50px;
          height: 30px;
          background: rgba(255, 16, 16, 1);
          border-radius: 16px;
          color: #fff;
          font-size: 14px;
          font-family: PingFangSC-Regular;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: -1px;
          line-height: normal;
        }
      }

      .brand-bg {
        width: 66px;
        height: 32px;
        background: #f2f2f2;
        border-radius: 16px;
      }
      .brand-bg-opacity {
        opacity: 0.15;
      }

      .brand {
        position: absolute;
        right: 10px;
        top: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 66px;
        height: 32px;
        border-radius: 16px;
        img {
          width: 20px;
          height: 20px;
        }

        p {
          font-size: 14px;
          color: #333333;
          line-height: normal;
        }
      }
    }

    .diamondlist {
      padding: 10px 0;
      display: flex;
      flex-wrap: wrap;
      .warp {
        margin-top: 10px;
      }
      .diamondlist__item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        min-width: 44px;
        width: 20%;

        .item__img {
          width: 43px;
          height: 43px;
        }

        .item__tit {
          padding-top: 4px;
          font-family: PingFangSC-Regular;
          font-size: 13px;
          color: #333333;
          text-align: center;
        }
      }
    }
  }
  .content {
    .content-top {
      margin-bottom: 8px;
      padding: 15px;
      background-color: #fff;
      border-radius: 10px;

      .tit {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10px;

        h3 {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }

        div {
          display: flex;
          align-items: center;
          font-size: 14px;
          color: #9b9b9b;
        }
      }

      .con {
        display: flex;
        flex-flow: row;

        .box {
          width: 16.66666%;

          div {
            width: 50px;
            height: 50px;
            background: rgba(245, 245, 245, 1) no-repeat center;
            border-radius: 2px;
            background-size: contain;
          }

          .symbol {
            text-align: center;
            line-height: 50px;
            font-weight: bold;
            color: #888;
          }
        }
      }
    }
  }
  // 卡片样式banner，下期优化样式再打开
  .index-banner {
    width: 100%;
    height: 120px;
  }
}
</style>
<style>
.DropdownMenu__wrap {
  background-color: #ffffff;
}
.DropdownMenu--wrap {
  margin-bottom: 8px;
}
</style>
